package com.doudanhua.basecode.jackson.configurer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/4 17:27
 */
public class DefaultJsonConfigurer implements JsonConfigurer {
    @Override
    public void config(ObjectMapper objectMapper) {
        //objectMapper.setAnnotationIntrospector(new NamingStrategyFieldSerializer());
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        //序列化时转为首字母大写字符串,反序列化时将属性名首字母转大写去匹配字符串
        //objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);


        // Long类型数字，在前端会出现精度丢失问题，要转换为string
        SimpleModule simpleModule = new SimpleModule();
        /*
        LongSerializer serializer = new LongSerializer();
        simpleModule.addSerializer(Long.class, serializer);
        simpleModule.addSerializer(long.class, serializer);
         */

        LongDeserializer deserializer = new LongDeserializer();
        simpleModule.addDeserializer(Long.class, deserializer);
        simpleModule.addDeserializer(long.class, deserializer);
        objectMapper.registerModule(simpleModule);

    }

    /**
     * Long类型数字，在前端会出现精度丢失问题，要转换为string
     */
    public static class LongSerializer extends JsonSerializer<Long> {
        @Override
        public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.toString());
        }
    }

    public static class LongDeserializer extends JsonDeserializer<Long> {
        @Override
        public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return p.getValueAsLong();
        }
    }
}
